package edu.cmu.cs.webapp.ioms.views;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.progress.UIJob;

import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.IngredientDAOImpl;
import edu.cmu.cs.webapp.ioms.logging.Alerts;
import edu.cmu.cs.webapp.ioms.models.Ingredient;
import edu.cmu.cs.webapp.ioms.ui.providers.ingredient.IngredientInforTableViewerContentProvider;
import edu.cmu.cs.webapp.ioms.ui.providers.ingredient.IngredientInforTableViewerLabelProvider;
import edu.cmu.cs.webapp.ioms.utils.IOMSUtils;
import edu.cmu.cs.webapp.ioms.utils.SWTUtils;



public class  IngredientInfoView extends ViewPart implements ISelectionProvider {
	public static final String ID_VIEW = "edu.cmu.cs.webapp.ioms.views.ingredientInfo";
	private TableViewer _viewer;
	private Combo _searchCombo;
	private Text _keywordSearch;
	private Table _table;
	private ITableLabelProvider labelProvider;
	private IngredientFilter viewerFilter;
	
	public static int INGREDIENT_ID=0;
	public static int INGREDIENT_NAME=1;
	public static int INGREDIENT_INVENTORY=2;
	public static int INGREDIENT_UNIT_COST=3;
	public static int INGREDIENT_REMARK=4;
	public static int INGREDIENT_DEMAND =5;
	
	
	
	private Ingredient[] ingredients;
	
	
	public void init(IViewSite site) throws PartInitException {
		super.init(site);
		site.setSelectionProvider(this);
	}
	
	public IngredientInfoView(){
		viewerFilter = new IngredientFilter();
		labelProvider = new IngredientInforTableViewerLabelProvider();
//		labelProvider = new ProductListTableViewerLableProvider();
	}
	
	public void createPartControl(Composite parent) {
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 1;
		gridLayout.marginHeight = 2;
		gridLayout.marginWidth = 2;
		
//		set the parent's layout
		parent.setLayout(gridLayout);

		Composite composite = new Composite(parent, SWT.NONE);
		GridData gridCompositeData = new GridData();
		gridCompositeData.verticalAlignment = GridData.BEGINNING;
		gridCompositeData.horizontalAlignment = GridData.FILL;
		gridCompositeData.grabExcessHorizontalSpace = true;

		composite.setLayoutData(gridCompositeData);

		GridLayout gridCompositeGroupLayout = new GridLayout();
		
//		this is to set the number of columns
		gridCompositeGroupLayout.numColumns = 3;
		composite.setLayout(gridCompositeGroupLayout);

		Label searchLabel = new Label(composite, SWT.NONE);
		searchLabel.setText("Search under:");

//		the second part of the column, previous label takes one seat
		_searchCombo = SWTUtils.createCombo(composite, new String[] {
				"Ingredient ID", "Ingredient Name", "Inventory Level","Unit Cost", "Remarks"}, 1);
		_searchCombo.select(0);

		_keywordSearch = new Text(composite, SWT.BORDER);
		GridData txtGridData = new GridData(GridData.FILL_HORIZONTAL);
		txtGridData.horizontalAlignment = SWT.FILL;
		txtGridData.grabExcessHorizontalSpace = true;
		_keywordSearch.setLayoutData(txtGridData);
		_keywordSearch.addModifyListener(new ModifyListener() {
			@Override
			public void modifyText(ModifyEvent event) {
				Text text = (Text) event.widget;
				viewerFilter.setText(text.getText());
				_viewer.refresh();
			}
		});

		createTableViewer(parent);
	}
	
	private void createTableViewer(Composite parent) {
		

		
		GridData gridData = new GridData();
		gridData.horizontalSpan = 3;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		gridData.horizontalAlignment = GridData.FILL;
		gridData.verticalAlignment = GridData.FILL;
		
//		here is to specify that its parent is parent;
		_table = new Table(parent, SWT.FULL_SELECTION | SWT.BORDER
				| SWT.H_SCROLL | SWT.V_SCROLL);
		_table.setLayoutData(gridData);

		_table.setHeaderVisible(true);
		_table.setLinesVisible(true);
		

		// ingredient id
		TableColumn idColumn = new TableColumn(_table, SWT.NONE);
		idColumn.setText("#"); 
		idColumn.setWidth(60);
		idColumn.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				int sortDirection = IOMSUtils
						.updateSortDirection((TableColumn) e.widget);
				_viewer.setSorter(new IngredientSorter(
						IngredientInforTableViewerLabelProvider.INGREDIENT_ID,
						sortDirection == SWT.DOWN));
			}
		});
		

		// ingredient name
		TableColumn nameColumn = new TableColumn(_table, SWT.NONE);
		nameColumn.setText("Ingredient Name"); 
		nameColumn.setWidth(100);
		nameColumn.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				int sortDirection = IOMSUtils
						.updateSortDirection((TableColumn) e.widget);
				_viewer.setSorter(new IngredientSorter(
						IngredientInforTableViewerLabelProvider.INGREDIENT_NAME,
						sortDirection == SWT.DOWN));
			}
		});
		
		// ingredient inventory 
		TableColumn inventoryColomn = new TableColumn(_table, SWT.NONE);
		inventoryColomn.setText("Inventory Level"); 
		inventoryColomn.setWidth(100);
		inventoryColomn.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				int sortDirection = IOMSUtils
						.updateSortDirection((TableColumn) e.widget);
				_viewer.setSorter(new IngredientSorter(
						IngredientInforTableViewerLabelProvider.INGREDIENT_INVENTORY,
						sortDirection == SWT.DOWN));
			}
		});
		
		// Ingredient unit cost
		TableColumn unitCostColumn = new TableColumn(_table, SWT.NONE);
		unitCostColumn.setText("Unit Cost"); 
		unitCostColumn.setWidth(100);
		unitCostColumn.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				int sortDirection = IOMSUtils
						.updateSortDirection((TableColumn) e.widget);
				_viewer.setSorter(new IngredientSorter(
						IngredientInforTableViewerLabelProvider.INGREDIENT_UNIT_COST,
						sortDirection == SWT.DOWN));
			}
		});
		
		
		
		// ingredient description
		TableColumn descColumn = new TableColumn(_table, SWT.NONE);
		descColumn.setText("Remarks"); 
		descColumn.setWidth(275);
		descColumn.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				int sortDirection = IOMSUtils
						.updateSortDirection((TableColumn) e.widget);
				_viewer.setSorter(new IngredientSorter(
						IngredientInforTableViewerLabelProvider.INGREDIENT_REMARKS,
						sortDirection == SWT.DOWN));
			}
		});
		
		// ingredient description
		TableColumn demandColumn = new TableColumn(_table, SWT.NONE);
		demandColumn.setText("Demand"); 
		demandColumn.setWidth(275);
		demandColumn.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				int sortDirection = IOMSUtils
						.updateSortDirection((TableColumn) e.widget);
				_viewer.setSorter(new IngredientSorter(
						IngredientInforTableViewerLabelProvider.INGREDIENT_REMARKS,
						sortDirection == SWT.DOWN));
			}
		});
				
		_viewer = new TableViewer(_table);
		_viewer.setUseHashlookup(true);
		_viewer.addFilter(viewerFilter);

		_viewer.setLabelProvider(labelProvider);
		_viewer.setContentProvider(new IngredientInforTableViewerContentProvider());
		

		refreshIngredientsView();
		
	}
	
	public static int updateSortDirection(TableColumn column) {
		Table table = column.getParent();
		if (column == table.getSortColumn()) {
			if (table.getSortDirection() == SWT.UP) {
				table.setSortDirection(SWT.DOWN);
			} else {
				table.setSortDirection(SWT.UP);
			}
		} else {
			table.setSortColumn(column);
			table.setSortDirection(SWT.DOWN);
		}
		return table.getSortDirection();
	}


	
	private class IngredientSorter extends ViewerSorter {
		private int columnIndex;
		private final boolean ascending;

		public IngredientSorter(int criteria, boolean ascending) {
			super();
//			specify which coloumn needs to be compared
			this.columnIndex = criteria;
			this.ascending = ascending;
		}

		@SuppressWarnings("unchecked")
		@Override
		public int compare(Viewer viewer, Object e1, Object e2) {
			int result = 0;
			if (e1 instanceof Ingredient && e2 instanceof Ingredient) {
				result = getComparator().compare(
						labelProvider.getColumnText(e1, columnIndex),
						labelProvider.getColumnText(e2, columnIndex));
			}

			if (!ascending) {
				result = result * -1;
			}
			return result;
		}
	}
	
	public void refreshIngredientsView() {
//		this._viewer.setInput(new DummieDataGenerator());
		UIJob refreshJob = new RefreshJob("Refresh");
		refreshJob.setUser(true);
		refreshJob.schedule();
	}
	
	private class RefreshJob extends UIJob {

		public RefreshJob(String name) {
			super(name);
		}

		@Override
		public IStatus runInUIThread(IProgressMonitor monitor) {
			monitor.beginTask("Refreshing Orders List...",
					IProgressMonitor.UNKNOWN);
			try {
				List<Ingredient> list = new IngredientDAOImpl().getAllIngr();
				
				ingredients = new Ingredient[list.size()];
				int i=0;
				for (Ingredient n : list){
					if (n!=null){
						ingredients[i]=n;
						i++;
					}
				}
			
			} catch (DataAccessException e) {
				Alerts.getInstance().detailError("Data Access Error",
						e.getLocalizedMessage(), e);
				return Status.CANCEL_STATUS;
			}

			if (ingredients != null) {
				_viewer.setInput(ingredients);
			}

			monitor.done();

			return Status.OK_STATUS;
		}
	}
	 

	private final class IngredientFilter extends ViewerFilter {
		private String text;

		public void setText(final String s) {
			this.text = s;
		}

		public boolean select(final Viewer viewer, final Object parentElement,
				final Object element) {
			boolean result = true;
			if (text != null && text.length() > 0) {
				String txt = labelProvider.getColumnText(element, _searchCombo
						.getSelectionIndex());
				result = txt.toLowerCase().indexOf(text.toLowerCase()) != -1;
			}
			return result;
		}

		public boolean isFilterProperty(final Object element, final String prop) {
			return true;
		}
	}

	
	
	
	@Override
	public void setFocus() {
		// TODO Auto-generated method stub
		
	}
	public void selectionChanged(SelectionChangedEvent event) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void addSelectionChangedListener(ISelectionChangedListener listener) {
		this._viewer.addSelectionChangedListener(listener);		
	}

	@Override
	public ISelection getSelection() {
		
		if (_viewer != null)
			return _viewer.getSelection();
		return null;
	}

	@Override
	public void removeSelectionChangedListener(
			ISelectionChangedListener listener) {
		this._viewer.removeSelectionChangedListener(listener);		

	}

	@Override
	public void setSelection(ISelection selection) {
		if (_viewer != null) {
			_viewer.setSelection(selection);
		}
	}
	
	/**
	 * 
	 * @param site
	 * @return
	 */
	public static IngredientInfoView getProductsListViewPart(IViewSite site) {
		
//		return the current view that is deployed in the workbench, then any other composite can called on this method to get the current view
		IViewPart view = site.getPage().findView(ProductView.ID_VIEW);
		if (view instanceof IngredientInfoView) {
			return ((IngredientInfoView) view);
		}
		return null;
	}
	

}
